
import React, { useEffect, useState } from 'react';
import { observer, useObserver } from 'mobx-react-lite';
import Image from 'next/image'
import { useStore } from '@/store';
import titleUrl from '@/styles/image/title.png'

import './index.scss'
import { Button, Form, Input, InputNumber, Popover, Select, notification } from 'antd';
import { createAiTextJob, getAiText } from '@/api';
const { TextArea } = Input;

function AiForm(props: { cb: (content: any, edit: any) => void }) {
  const store = useStore()
  const [form] = Form.useForm();

  const handleEditorChange = (content: any, edit: any) => {
    props.cb(content, edit)
  }
  const addPoint = () => {
    if (!store.user?.userInfo?.id) {
      store.user.setOpenLoginModal(true)
      return;
    }
    store.user.changePayModalStatus(true)
  }

  const submit = () => {
    if (store?.user?.pointNum === 0) {
      addPoint()
    }
    /**添加面罩 */
    form.validateFields().then(
      async (param) => {
        const res = await createAiTextJob({
          promt_type: 'aiwrite',
          promt: store.cateConfig.aiCateConfig.prompt.replace(/\$\{(\w+)\}/g, replaceTemplates),
          num: param.word || 1000,
          fileid: '1',
          cateid: store.cateConfig.aiCateConfig.cateid
        })

        function replaceTemplates(match: string, key: string) {
          return param[key];
        }

        if (res.code) {
          store.editorInfo.setProcessStatus(true);
          if (store.editorInfo.editorHandle.current && store.editorInfo.editorHandle.current.editor && store.editorInfo.editorHandle.current.editor.iframeElement) {
            store.editorInfo.editorHandle.current.editor.iframeElement.style.zIndex = '-1'
          }
          getAiText({
            id: res.data.id,
            timestamp: res.data.timestamp,
            nonce: res.data.nonce,
            sign: res.data.sign,
            num: param.word || 1000,
            promt_type: 'aiwrite',
            promt: store.cateConfig.aiCateConfig.prompt.replace(/\$\{(\w+)\}/g, replaceTemplates),
          }, async (response: Response) => {
            const stream = response.body;
            if (stream && stream.getReader) {
              const reader = stream.getReader();

              reader.read().then(function process({ done, value }): any {
                if (done) {
                  //状态设置
                  store.editorInfo.setProcessStatus(false);
                  //点数控制
                  store.user.fetchUserPoint();
                  if (store.editorInfo.editorHandle.current && store.editorInfo.editorHandle.current.editor && store.editorInfo.editorHandle.current.editor.iframeElement) {
                    store.editorInfo.editorHandle.current.editor.iframeElement.style.zIndex = '100'
                  }
                  //保存文本
                  store.fileMagage.postRecord({
                    record: store.editorInfo.editorHandle.current.editor.getContent({ format: 'raw' })
                  })
                  return;
                }

                let buffer = new TextDecoder('utf-8').decode(value);
                const lines = buffer.replaceAll('event:message', '').split('\ndata:');
                lines.forEach(line => {
                  if (line != '') {
                    try {
                      const json = JSON.parse(line);
                      if (json.msg == 'ok') {
                        // const content= store.editorInfo.editorHandle.current.editor.getContent({ format: 'raw' });
                        const htmlText = (json.data.replaceAll('\n', '<p style="text-indent: 2em; margin:0">'))
                        store.editorInfo.editorHandle.current.editor.insertContent(htmlText, { format: 'raw' })
                      }

                    } catch (e) { }
                    //  store.editorInfo.editorHandle.current.editor.setContent(content+line)
                  }
                });

                // Continue reading
                return reader.read().then(process);
              });
            }
          }).catch(res => {
            store.editorInfo.setProcessStatus(false);
            store.user.fetchUserPoint();
            if (store.editorInfo.editorHandle.current && store.editorInfo.editorHandle.current.editor && store.editorInfo.editorHandle.current.editor.iframeElement) {
              store.editorInfo.editorHandle.current.editor.iframeElement.style.zIndex = '100'
            }
          }).finally(() => {  
          })
        } else {
          notification.info({ message: res.msg })
        }

      },
      () => {
        // notification.error({ message: '验证失败' })
      },
    );
  }
  return (
    <div className=' w-full h-auto p-10'>
      <Form name="form_item_path" layout="vertical" form={form}>
        {store.cateConfig.aiCateConfig.list.map((val, key) => {
          let node
          switch (val.type) {
            case 'text':
              node =
                <Form.Item key={key} label={val.title} name={val.name} rules={[{ required: true, message: val.placeholder }]}>
                  <Input className=' h-r4.0' placeholder={val.placeholder}></Input>
                </Form.Item>

              break;
            case 'textarea':
              node =
                <Form.Item key={key} label={val.title} name={val.name} rules={[{ required: true, message: val.placeholder }]}>
                  <TextArea rows={4} className=' h-r4.0' placeholder={val.placeholder}></TextArea>
                </Form.Item>

              break;
            // case 'number':
            //   node = <>
            //     <Form.Item label={val.title} name={val.name} rules={[{ required: true, message: val.placeholder }]}>
            //       <InputNumber
            //         className=' h-r4.0'
            //         placeholder="不小于100字，大于800字"
            //         style={{ width: '100%', lineHeight: '4.0rem' }}></InputNumber>
            //     </Form.Item>
            //   </>
            //   break;
            case 'select':
              node =
                <Form.Item key={key} label={val.title} initialValue={val.option.split(',').length > 0 ? val.option.split(',')[0] : ''} name={val.name} rules={[{ required: true, message: val.placeholder }]}>
                  <Select >
                    {val.option.split(',').map((v, k) => {
                      return (<Select.Option key={k} value={v}>{v}</Select.Option>)
                    })}
                  </Select>
                </Form.Item>
              break;
            default:
              node = <></>
          }

          return node
        })}
        {/* <Form.Item label="职位" name="promt_type" rules={[{ required: true, message: '请描述您的岗位， 如：产品经理' }]}>
          <Input className=' h-r4.0' placeholder="请描述您的岗位， 如：产品经理"></Input>
        </Form.Item>
        <Form.Item label="工作内容" name="promt" rules={[{ required: true, message: '概述您的工作内容即可' }]} >
          <Input className=' h-r4.0' placeholder="概述您的工作内容即可"></Input>
        </Form.Item> */}
        <div className=' text-center' >
          <Button className=' w-r14.0 h-r5.0' onClick={() => { form.resetFields(store.cateConfig.aiCateConfig.list.map(val => val.name)) }} >清空录入</Button>
          <Popover content={<div>每次消耗1点</div>} title="提示" trigger="hover">
            <Button className=' ml-5 w-auto min-w-r14.0  h-r5.0' style={{ backgroundColor: '#0A0B17', color: '#ffff', height: '5.0rem' }} disabled={store.editorInfo.isProcess} onClick={submit} >{store.editorInfo.isProcess ? 'AI正在思考🤔.....' : '生成内容'}</Button>
          </Popover>
        </div>
      </Form>


    </div>
  );
}
export default observer(AiForm)

